package com.sin.j2me.update;

import org.json.me.JSONArray;
import org.json.me.JSONObject;

import com.sin.j2me.common.ExceptionHandle;
import com.sin.j2me.framework.SinUtil;

public class CheckUpdate {
	public static final String URL = "http://sinzone.freevar.com/updatecheck/checkupdate.php";
//	public static final String URL = "http://127.0.0.1/php/updatecheck/checkupdate.php";
	
	public static String getJson(String updateid, String version){
		String url = URL+"?"+"updateid="+updateid+"&version="+version;
		String res =SinUtil.HttpGet(url);
		return res;
	}
	
	public static UpdateObject getUpdate(String updateid, String version){
		String json = getJson(updateid, version);
		UpdateObject obj = null;
		try{
			JSONObject j = new JSONObject(json);
			if(j.getInt("status") == 0){
				JSONArray array = j.getJSONArray("items");
				if(array.length()>0){
					JSONObject o = array.getJSONObject(0);
					obj = new UpdateObject();
					obj.setVersion(o.getString("version"));
					obj.setMessage(o.getString("message"));
					obj.setDetail(o.getString("detail"));
					obj.setTime(o.getString("time"));
					obj.setUrl(o.getString("url"));
				}
			}
		}
		catch(Exception e){
			obj = null;
			e.printStackTrace();
			ExceptionHandle.handle(e);
		}
		return obj;
	}

	public static void checkUpdate(String updateid, String version, WhenUpdate whenUpdate) {
		Thread thread = new CheckUpdateThread(updateid, version, whenUpdate);
		thread.start();
	}
	
	
	static public class CheckUpdateThread extends Thread{
		private String updateid;
		private String version;
		private WhenUpdate whenUpdate;
		public CheckUpdateThread(String updateid, String version,
				WhenUpdate whenUpdate) {
			super();
			this.updateid = updateid;
			this.version = version;
			this.whenUpdate = whenUpdate;
		}

		public void run() {
			UpdateObject update = getUpdate(updateid, version);
			if(update!=null && whenUpdate!=null){
				whenUpdate.whenUpdate(update);
			}
		}
	}
}
